//
//  Upload.m
//  UploadFnta
//
//  Created by Florent Jardin on 30/11/09.
//  Copyright 2009 fnta.me All rights reserved.
//

#import "Upload.h"


@implementation Upload
@synthesize filename;

-(id)init:(NSString *)pathString {
	filename = pathString;
	return self;
}

-(NSString*)uploadFile:(NSString*)urlString objectName:(NSString*)objName {
	//creating the url request:
	NSURL *url = [NSURL URLWithString:urlString];
	NSMutableURLRequest *postRequest = [NSMutableURLRequest requestWithURL:url];

	//adding header information:
	[postRequest setHTTPMethod:@"POST"];

	NSString *stringBoundary = [NSString stringWithString:@"0xKhTmLbOuNdArY"];
	NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",stringBoundary];
	[postRequest addValue:contentType forHTTPHeaderField:@"Content-Type"];


	//setting up the body:
	NSMutableData *postBody = [NSMutableData data];
	[postBody appendData:[[NSString stringWithFormat:@"--%@\r\n",stringBoundary] dataUsingEncoding:NSUTF8StringEncoding]];	
	[postBody appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"; filename=\"%@\"\r\n", objName, [filename lastPathComponent]]
						  dataUsingEncoding:NSUTF8StringEncoding]];
	[postBody appendData:[[NSString stringWithString:@"Content-Type: application/octet-stream\r\n\r\n"]
						  dataUsingEncoding:NSUTF8StringEncoding]];
	[postBody appendData:[NSData dataWithContentsOfFile:filename]];
	[postBody appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",stringBoundary]
						  dataUsingEncoding:NSUTF8StringEncoding]];
	[postRequest setHTTPBody:postBody];

	//sending the request via NSURLConnection:
	NSData *returnData = [NSURLConnection sendSynchronousRequest:postRequest returningResponse:nil error:nil];
	NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
	
	return returnString;
}

@end
